<?php
namespace app\api\controller;

use think\Controller;
use think\Request;
use think\Loader;
use think\Db;
use think\Config;

use app\common\BaseController;
use app\model\UserModel;
use app\model\AppointmentModel;
use app\model\MeetingModel;
use app\model\CodeModel;
use app\model\ArriveModel;

/**工具**/
use app\common\Tool\ApiErrDesc;
use redis\Redis;

class Arrive extends BaseController
{
    private $wechatOA;
    private $table_meeting_view = 'view_new_app_meeting_info';
    private $table_arrived = 'arrive';

    public function _initialize(){
        $this->redis = new Redis();
        $this->noNeedLogin = [];
        Loader::import('Wechat_OA', EXTEND_PATH);
        $this->wechatOA = new \Wechat_OA();
    } 
  
    /**
     * [arrive_info description]
     * @auth         true
     * @throws           hink\Exception
     * @throws           hink\exception\PDOException
     * @HtttpRequest                              get|post
     * @Author       X
     * @Param
     * @DateTime     2020-09-16T15:49:52+0800
     * @LastTime     2020-09-16T15:49:52+0800
     * @return       [type]                       [description]
     */
    public function arrive_info(){
        $companyid = trim($this->request->param('companyid'));
        $position = trim($this->request->param('position'));
        $meetingid = trim($this->request->param('meetingid'));

        if(!empty($meetingid)){
            $data = $this->find($this->table_meeting_view,'id = '.$meetingid);
            return toJson(['message'=>'获取信息成功','code'=>200,'data'=>$data]);
        }
        
        if(empty($companyid) || empty($position)){
            return toJson(['message'=>'参数不全，请检查','code'=>400]);
        }
        
        
        $meetingData = MeetingModel::where('uid',$this->uid)->where('appointment_companyid',$companyid)->select();
        if(empty($meetingData)){
            return toJson(['message'=>'信息不存在','code'=>400]);
        }

        return toJson(['message'=>'获取信息成功','code'=>200,'data'=>$meetingData]);
    }



    public function arrive(){
        $id = trim($this->request->param('meetingid'));

        if(empty($id)){
            return toJson(['message'=>'邀请ID不能为空','code'=>400]);
        }

        $arriveData = new ArriveModel;
        $arriveData->uid = $this->uid;
        $arriveData->meetingid = $id;
        $arriveData->createtime = time();
        $arriveData->save();

        return toJson(['message'=>'接受邀请成功','code'=>'200']);
    }

    /*用户到达门口
    *推送保安
    *推送受访人
    *查出访客 信息(包括见面信息)
    *调用接口角色: 访客----保安
    */
   /**
    * [arrived description]
    * @HtttpRequest                          get|post
    * @Author       X|GNLEON
    * @Param
    * @DateTime     2020-09-02T10:45:47+0800
    * @LastTime     2020-09-02T10:45:47+0800
    * @return       [type]                   [description]
    * @remark       扫码业务逻辑 暂时先写在这 code模块 为新扫码接口，
    *               按时根据需求去除 本方法下的扫码逻辑
    */
    public function arrived(){
        // $this->user['roleid']=6;
        Loader::import('Wechat_OA', EXTEND_PATH);
        $wechatOA = new \Wechat_OA();
        $uid = trim($this->request->param('uid'))?:$this->uid;
        $companyid = trim($this->request->param('companyid'));
        $meeting_code = trim($this->request->param('meeting_code'));
        $doornum = trim($this->request->param('door'));
        $today = strtotime(date("Y-m-d"),time());
        $offset = trim($this->request->param('offset'))?:1;
        $length = trim($this->request->param('length'))?:999;
        $enddaytime = $today+60*60*24;

        /**保安扫码**/
        if($this->user['companyid'] == $companyid && ($this->user['roleid']==6 || $this->user['roleid'] ==5)){

            $where = 'companyid = '.$companyid.' and appointment_status = 0 and arrive_status not in(4,5) and app_visittime between '.$today.' and '.$enddaytime;
            $order = 'app_visittime desc';

            $data = $this->selectView($this->table_meeting_view, $where, $field = '*', $offset, $length, $order);
            $count = $this->total($this->table_meeting_view, $where, $field = '*');

            return toJson(['message'=>'Success_保安访客列表','code'=>200,'data'=>$data,'count'=>$count,'requestTime'=>time()]);
        } 

        // if(empty($uid)){
        //     return toJson(['message'=>'邀请ID不能为空','code'=>400]);
        // }

        $u_Appointment = Db::table('view_new_app_meeting_info')
                        ->where('vister_uid = '.$uid.' and companyid = '.$companyid.' and appointment_status = 0')
                        ->where('app_visittime','between time',[$today,$enddaytime])
                        ->order('app_visittime desc')
                        ->find();

        // var_dump($u_Appointment);
        $time=date('Y-m-d',$u_Appointment['app_visittime']);
        $now=date("Y-m-d",time());
        if(!$u_Appointment){
            return toJson(['message'=>'Faild','code'=>400]);
        }
        /*自行离开-推送保安-*/
        if($u_Appointment['arrive_status'] == 3  || $u_Appointment['arrive_status'] ==2 || $u_Appointment['arrive_status'] == 6){
            $check_company_type = $this->find('view_company','id = '.$companyid);
            if($check_company_type['type'] == 1){
                $true_companyid = $this->find('property_relation','incompany_id = '.$companyid);
                $companyid = $true_companyid['property_id'];
                $security = Db::table('view_user')->where('roleid = 6 and companyid = '.$companyid)->select();
            }else{
                $security = Db::table('view_user')->where('roleid = 6 and companyid = '.$companyid)->select();
            }   
            
            $url = 'http://devs.zsicp.com/h5/#/pages/securityguard/useraudit?companyid='.$companyid.'&meetingid='.$u_Appointment['id'].'&door=A';
            /*推给保安*/
            if($time==$now){
            foreach ($security as $key => $value) {

                $openid = $value['openid']; 
                // $url = '';
                $data = [
                'template_id' => 'NrON2M_fanQcweteHXRpWrWbPuerflXMNGfB13EFD_0',
                'array' => [
                    'first' => "访客{{$this->user->name}}到达门口,请检查放行",
                    'keyword1' => date('Y-m-d H:i:s',time($u_Appointment['app_visittime'])),
                    'keyword2' =>  $this->user->name,
                    'keyword3' =>  $u_Appointment['app_reson'],
                    'keyword4' => date('Y-m-d H:i:s',time()),
                    'keyword5' => '公司门口',
                    'remark'   => '请及时确认放行.'
                    ],
                ];
                $result = $wechatOA->send_WXtpl($openid,$data,$url);
                
            }
    
            }
            return toJson(['message' => '已通知保安','code' => 200]);
        }
        /*END*/

        /**用户扫公司永久二维码到达**/
        $arriveData = ArriveModel::where('meetingid',$u_Appointment['id'])
                                ->where('uid',$this->uid)
                                // ->where('companyid',$companyid)
                                ->where('status',0)
                                ->find();
        if(empty($arriveData)){
            return toJson(['message'=>'信息不存在','code'=>400]);
        }
        $where = 'meetingid = '.$u_Appointment['id'].' and uid ='.$this->uid.' and status = 0';

        $data = [
            'status' =>  1,
            'arrivetime' => time(),
        ];
        $res = $this->update('arrive', $where, $data);
        if(!$res){return toJson(['message'=>'Faild1','code'=>400]);}

        /*查出保安-推送*/
        $check_company_type = $this->find('view_company','id = '.$companyid);
        if($check_company_type['type'] == 1){
            $true_companyid = $this->find('property_relation','incompany_id = '.$companyid);
            $companyid = $true_companyid['property_id'];
            $security = Db::table('view_user')->where('roleid = 6 and companyid = '.$companyid)->select();
        }else{
            $security = Db::table('view_user')->where('roleid = 6 and companyid = '.$companyid)->select();
        }
        

        $url = 'http://devs.zsicp.com/h5/#/pages/securityguard/useraudit?companyid='.$companyid.'&meetingid='.$u_Appointment['id'].'&door=A';
        /*推给保安*/
        if($time==$now){
        foreach ($security as $key => $value) {

            $openid = $value['openid']; 
            $data = [
            'template_id' => 'NrON2M_fanQcweteHXRpWrWbPuerflXMNGfB13EFD_0',
            'array' => [
                'first' => "访客{{$this->user->name}}到达门口,请检查放行",
                'keyword1' => date('Y-m-d H:i:s',time($u_Appointment['app_visittime'])),
                'keyword2' =>  $this->user->name,
                'keyword3' =>  $u_Appointment['app_reson'],
                'keyword4' => date('Y-m-d H:i:s',time()),
                'keyword5' => '公司门口',
                'remark'   => '请及时确认放行.'
                ],
            ];
            $result = $wechatOA->send_WXtpl($openid,$data,$url);
            
        }

        $app_uinfo = $this->find('view_user','id = '.$u_Appointment['app_uid']);
        if(empty($app_uinfo)){return toJson(['message'=>'Faild2','code'=>400]);}
        $url = 'http://devs.zsicp.com/h5/#/pages/yuyuejilu/recordDetails?detaildata=';
        $urldata = [
            'id' => $u_Appointment['appointmentid'],
            'showtype' => 2,
            'appinfo' => $u_Appointment
        ];
        $url = $url.json_encode($urldata);
        /*推给受访人*/

        $openid = $app_uinfo['openid']; 
        $data = [
        'template_id' => 'NrON2M_fanQcweteHXRpWrWbPuerflXMNGfB13EFD_0',
        'array' => [
            'first' => "访客{{$this->user->name}}到达公司门口",
            'keyword1' => date('Y-m-d H:i:s',time($u_Appointment['app_visittime'])),
            'keyword2' =>  $this->user->name,
            'keyword3' =>  $u_Appointment['app_reson'],
            'keyword4' => date('Y-m-d H:i:s',time()),
            'keyword5' => '访客到达',
            'remark'   => '请做好接待访客准备.'
            ],
        ];
        $result = $wechatOA->send_WXtpl($openid,$data,$url);
          
        /*推给访客--自己*/
        $url = '';
        $data = ['title'=>'到达保安门口通知',
                'openid'=>$this->user->openid,
                'name'=>$this->user->name,
                'mobile'=>$this->user->mobile,
                'visittime'=>date('Y-m-d H:i:s',$u_Appointment['app_visittime']),
                'status'=>'到达保安门口',
                'remark'=>"您到达保安门口,请等待放行.",
                'url'=>$url
        ];
        $result = $wechatOA->send_message($data);
        
      
        
        return toJson(['message'=>'到达保安门口成功','code'=>'200']);

        }else{
            return toJson(['message'=>'请在指定预约时间到达','code'=>'400']);
        }
    }
    
    public function arrived_code(){
        $companyid = trim($this->request->param('companyid'));
    
        if(empty($companyid)){
            return toJson(['message'=>'参数不全，请检查','code'=>400]);
        }
    
        $arriveData = ArriveModel::where('uid',$this->uid)->where('companyid',$companyid)->where('status',0)->select();
        if(empty($arriveData)){
            return toJson(['message'=>'信息不存在','code'=>400]);
        }
    
        return toJson(['message'=>'获取信息成功','code'=>200,'data'=>$arriveData]);
    }
    /**
     * @Author      x
     * @HttpRequest                            |post
     * @Param
     * appid---邀请id    
     * uid-保安id(该公司管理级别人员也可) - --
     * meetingid ---meeting表id(查arrive表)                -
     * @DateTime    
     * @LastTime                2020-07-25
     * @copyright   [copyright]
     * @license     [license]
     * @return      [type]      [description]
     */
    public function accept_post(){
        $id = trim($this->request->param('appid'));
        $uid = trim($this->request->param('uid'));
        // $url = trim($this->request->param('url'));
        $meetingid = trim($this->request->param('meetingid'));

        if(empty($meetingid)){
            return toJson(['message'=>'ID不能为空','code'=>400]);
        }
        // if(empty($id)){
        //     return toJson(['message'=>'邀请ID不能为空','code'=>400]);
        // }
        $appointmentData = $this->find($this->table_meeting_view,'id = '.$meetingid.' and arrive_status != 5');

        // $appointmentData = AppointmentModel::alias('app')
        //                                     ->field('app.*,user.openid,user.name as uname,user.mobile')
        //                                     ->join('user','app.uid=user.id','left')
        //                                     ->where('app.id','eq',$id)
        //                                     ->find();
        if(empty($appointmentData)){
            return toJson(['message'=>'邀请信息不存在','code'=>'400']);
        }
        if($appointmentData['arrive_status'] == 2){ return toJson(['message'=>'信息已确认,无需重复操作.','code'=>'400']);}

        $where = 'meetingid = '.$meetingid.' and uid = '.$appointmentData['vister_uid'];
        $data =  [
            'passtime' => time(),
            'status' => 2
        ];
        $updata = $this->update('arrive', $where, $data);

        if($updata!=true){return toJson(['message'=>$updata['message'],'code'=>400]);} 
        // $meetingData = MeetingModel::where('appointmentid ='.$appointmentData['appointmentid'].' and uid = '.$appointmentData['vister_uid'])->find();
        // if(empty($meetingData)){
        //     return toJson(['message'=>'信息不存在','code'=>'400']);
        // }

        // $meetingData = new MeetingModel;
        // $meetingData->uid = $appointmentData[''];
        // $meetingData->companyid = $this->user->companyid;
        // $meetingData->appointmentid = $id;
        // $meetingData->appointment_companyid = $appointmentData->companyid;
        // $meetingData->status = 2;
        // $meetingData->createtime = time();
        // $meetingData->save();
        $u_appInfo = $this->find('view_user','id ='.$appointmentData['app_uid']);
        $u_visterInfo = $this->find('view_user','id ='.$appointmentData['vister_uid']);

        /*插入延迟推送*/
        $data = [
            'uid' => $u_visterInfo['id'],
            'openid' => $u_visterInfo['openid'],
            'appointmentid' => $appointmentData['appointmentid'],
            'arriveid' => $appointmentData['arrive_id'],
            'meetingid' => $appointmentData['id'],
            'expiretime' => time()+(60*5),
            'createtime' => time()

        ];
        $res_send = $this->insert('wx_tmplate_message', $data);

        if(!$res_send){return toJson(['message'=>'Faild','code'=>400]);}
        

        /*推送三方*/
        $url ='http://devs.zsicp.com/h5/#/pages/yaoqing/xiangqing?detailDate=';
        $appointmentData['id'] = $appointmentData['appointmentid'];
        $urldata = json_encode($appointmentData);
        $url = $url.$urldata;
        Loader::import('Wechat_OA', EXTEND_PATH);
        $wechatOA = new \Wechat_OA();
        $nowtime = strtotime(date("Y-m-d H:i:s"),time());
        /*受访人*/
        $data = ['title'=>'确认进入通知',
                'openid'=>$u_appInfo['openid'],
                'name'=>$u_visterInfo['name'],
                'mobile'=>$u_visterInfo['mobile'],
                'visittime'=>date('Y-m-d H:i:s',$appointmentData['app_visittime']),
                'status'=>'确认进入',
                'remark'=>"门卫:{$this->user->name},确认进入",
                'url'=>$url
        ];
        $result = $wechatOA->send_message($data);

        /*保安-*/
        $url = 'http://devs.zsicp.com/h5/#/pages/securityguard/useraudit?companyid='.$u_appInfo['companyid'].'&meetingid='.$meetingid.'&door=A';
        $data = ['title'=>'确认进入通知',
                'openid'=>$this->user->openid,
                'name'=>$u_visterInfo['name'],
                'mobile'=>$u_visterInfo['mobile'],
                'visittime'=>date('Y-m-d H:i:s',$appointmentData['app_visittime']),
                'status'=>'确认进入',
                'remark'=>"您确认了{$u_visterInfo['name']}的进入",
                'url'=>$url
        ];
        $result = $wechatOA->send_message($data);
        // 访客
          $url ='http://devs.zsicp.com/h5/#/pages/yaoqing/xiangqing?detailDate=';
          $appointmentData['id'] = $appointmentData['appointmentid'];
          $urldata = json_encode($appointmentData);
          $url = $url.$urldata;
          $data = ['title'=>'确认进入通知',
                'openid'=>$u_visterInfo['openid'],
                'name'=>$u_visterInfo['name'],
                'mobile'=>$u_visterInfo['mobile'],
                'visittime'=>date('Y-m-d H:i:s',$appointmentData['app_visittime']),
                'status'=>'确认进入',
                'remark'=>"确认了{$u_visterInfo['name']}的进入",
                'url'=>$url
        ];
        $result = $wechatOA->send_message($data);
        
        return toJson(['message'=>'确认进入成功','code'=>'200']);
    }
    
    
    public function accept_code(){
        $companyid = trim($this->request->param('companyid'));
    
        if(empty($companyid)){
            return toJson(['message'=>'参数不全，请检查','code'=>400]);
        }
    
        $arriveData = ArriveModel::where('uid',$this->uid)->where('companyid',$companyid)->where('status',1)->select();
        if(empty($arriveData)){
            return toJson(['message'=>'信息不存在','code'=>400]);
        }
    
        return toJson(['message'=>'获取信息成功','code'=>200,'data'=>$arriveData]);
    }
    /**
     * @Author      x
     * @HttpRequest                            |post
     * @Param       uid放行人id meetingid             -
     * @DateTime  
     * @LastTime                2020-07-26
     * @copyright   [copyright]
     * @license     [license]
     * @return      [type]      [description]
     */
    public function refuse_post(){
        $uid= trim($this->request->param('uid'));
        $meetingid = trim($this->request->param('meetingid'));
        $remark = trim($this->request->param('refuseremark'))?:'无';
        $url =  trim($this->request->param('url'))?:'';

        if(empty($uid)){
            return toJson(['message'=>'参数错误','code'=>400]);
        }
        /*检查保安权限*/
        $checkrole = $this->find('view_user','id = '.$uid);
        if(empty($checkrole)){return toJson(['message'=>'用户不存在','code'=>400]);}
        //if($checkrole['roleid'] != 6){return toJson(['message'=>'没有此权限','code'=>400]);}

        if(!empty($meetingid)){
            $data = $this->find($this->table_arrived,'meetingid = '.$meetingid);
            if(empty($data)){
                return toJson(['message'=>'信息不存在','code'=>400]);
                }
        }

        $meetingData = $this->find('meeting','id = '.$meetingid);
        if(empty($meetingData)){
            return toJson(['message'=>'信息不存在','code'=>400]);
        }

        // $arriveData = $this->find('arrive','meetingid = '.$meetingid.' and status = 1');
        // if(empty($arriveData)){
        //     return toJson(['message'=>'访客未到达','code'=>400]);
        // }

        $where = 'id = '.$meetingid;
        $data =  [
            'security_uid' => $uid
        ];
        $updata = $this->update('meeting', $where, $data);
        if(!$updata){return toJson(['message'=>'信息不存在','code'=>400]);} 

        //$where = 'meetingid = '.$meetingid.' and status = 1';
        $where = 'meetingid = '.$meetingid.' and (status = 1 or status = 0)';
        $data =  [
            'refusetime' => time(),
            'status' => 5,
            'refuseremark' => $remark
        ];
        $updata = $this->update('arrive', $where, $data);
        if(!$updata){return toJson(['message'=>'信息不存在','code'=>400]);} 

        /*推送三方*/
        $u_Appointment = $this->find($this->table_meeting_view,'id ='.$meetingid);
        if(empty($u_Appointment)){return toJson(['message'=>'见面信息不存在','code'=>400]);}
        $u_visterInfo = $this->find('view_user','id = '.$u_Appointment['vister_uid']);
        $u_appInfo  = $this->find('view_user','id = '.$u_Appointment['app_uid']);
        // $u_securityInfo = $this->find('view_user','id ='.$meetingData['security_uid']);

        Loader::import('Wechat_OA', EXTEND_PATH);
        $wechatOA = new \Wechat_OA();
        /*受访人*/
        $data = ['title'=>'拒绝进入通知',
                'openid'=>$u_appInfo['openid'],
                'name'=>$u_visterInfo['name'],
                'mobile'=>$u_visterInfo['mobile'],
                'visittime'=>date('Y-m-d H:i:s',$u_Appointment['app_visittime']),
                'status'=>'拒绝进入',
                'remark'=>"访客{$u_visterInfo['name']}被拒绝进入,原因:{$remark}",
                'url'=>$url
        ];
        $result = $wechatOA->send_message($data);

        /*保安*/
        $data = ['title'=>'拒绝进入通知',
                'openid'=>$this->user->openid,
                'name'=>$u_visterInfo['name'],
                'mobile'=>$u_visterInfo['mobile'],
                'visittime'=>date('Y-m-d H:i:s',$u_Appointment['app_visittime']),
                'status'=>'拒绝进入',
                'remark'=>"访客{$u_visterInfo['name']}被拒绝进入,原因:{$remark}",
                'url'=>$url
        ];
        $result = $wechatOA->send_message($data);

        /*访客-自己*/
        $data = ['title'=>'拒绝进入通知',
                'openid'=>$u_visterInfo['openid'],
                'name'=>$u_visterInfo['name'],
                'mobile'=>$u_visterInfo['mobile'],
                'visittime'=>date('Y-m-d H:i:s',$u_Appointment['app_visittime']),
                'status'=>'拒绝进入',
                'remark'=>"您被拒绝进入,原因:{$remark}",
                'url'=>$url
        ];
        $result = $wechatOA->send_message($data);

        return toJson(['message'=>'拒绝进入成功','code'=>'200']);
    }

    public function confirm_code(){
        $companyid = trim($this->request->param('companyid'));

        if(empty($companyid)){
            return toJson(['message'=>'参数不全，请检查','code'=>400]);
        }

        $arriveData = ArriveModel::where('uid',$this->uid)->where('companyid',$companyid)->where('status',2)->select();
        if(empty($arriveData)){
            return toJson(['message'=>'信息不存在','code'=>400]);
        }

        return toJson(['message'=>'获取信息成功','code'=>200,'data'=>$arriveData]);
    }
    /**部门二维码
     * [confirm description]
     * 访客到达具体地点--不传uid
     * 代签列表--传邀请人uid
     * 邀请人代签--传访客uid
     * @HtttpRequest                          |post
     * @Author       x
     * @param [type] $[name] [<description>]        
     *                 uid    访客uid-|waring--570--为邀请人uid
     *                 type   代签列表----list  leave----代离开  myleave -----自行离开
     * @DateTime     
     * @LastTime     2020年8月6日14:10:02-566-567
     * @return       [type]                   [description]
     * @remark       564--warning!!--
     */
    public function confirm(){

        $uid = trim($this->request->param('uid'))?trim($this->request->param('uid')):$this->uid;
        $companyid = trim($this->request->param('companyid'));
        $deptid  = trim($this->request->param('deptid'));
        $url = trim($this->request->param('url'))?:'';
        $type = trim($this->request->param('type'))?:'';
        $offset = trim($this->request->param('offset'))?:0;
        $length = trim($this->request->param('length'))?:10;

        $today = strtotime(date("Y-m-d"),time());
        $enddaytime = $today+60*60*24;

        /*判断访客or邀请人*/
        if($type!='list'){
            $where = 'companyid = '.$companyid.' and deptid = '.$deptid.' and status = 0 and uid = '.$uid.' and visittime between '.$today.' and '.$enddaytime;
            $u_check = $this->find('appointment', $where)!=NULL?$u_check = 'app':$u_check = 'vister';

            $where = 'vister_uid = '.$uid.' and companyid = '.$companyid.' and deptid = '.$deptid.' and appointment_status = 0 and arrive_status in (2,3) and app_visittime between '.$today.' and '.$enddaytime;
            $u_check_vister = $this->total($this->table_meeting_view, $where, $field = '*')==0?$u_check = $u_check:$u_check = 'vister';
       }
        $type == 'list'?$u_check = 'app':'';

        // var_dump($u_check_vister);
        // exit();
        /*代签列表*/
        if($u_check=='app'){

            $where = 'app_uid = '.$uid.' and companyid = '.$companyid.' and deptid = '.$deptid.' and appointment_status = 0 and arrive_status in (2,3) and app_visittime between '.$today.' and '.$enddaytime;
            $order = 'passtime desc';

            $data = $this->selectView($this->table_meeting_view, $where, $field = '*', $offset, $length, $order);

            $count =  $this->total($this->table_meeting_view, $where, $field = '*');

            return toJson(['message'=>'Success_代签表列','code'=>200,'data'=>$data,'count'=>$count,'requestTime'=>time()]);
        }
        $type == 'leave'?$where = 'vister_uid = '.$uid.' and companyid = '.$companyid.' and appointment_status = 0 and arrive_status = 3':'vister_uid = '.$uid.' and companyid = '.$companyid.' and appointment_status = 0 and arrive_status in(2,3)';

        $u_Appointment = Db::table('view_new_app_meeting_info')
                ->where($where)
                ->where('app_visittime','between time',[$today,$enddaytime])
                ->order('app_visittime desc')
                // // ->where('appointment_creatime','between time',[$today,$enddaytime])
                // ->order('appointment_creatime desc')
                ->find();
        if(!$u_Appointment){
            return toJson(['message'=>'信息不存在','code'=>400]);
        }

        $tmparrive_status = $u_Appointment['arrive_status'];

        $type == 'leave'?$where = ' status = 3':$where = ' status = '.$tmparrive_status;
        $arriveData = ArriveModel::where('meetingid',$u_Appointment['id'])
                        ->where('uid',$uid)
                        // ->where('companyid',$companyid)
                        ->where($where)
                        ->find();
        if(empty($arriveData)){
            return toJson(['message'=>'信息不存在','code'=>400]);
        }
        
        $type == 'leave'?$where = 'meetingid = '.$u_Appointment['id'].' and uid ='.$uid.' and status = 3':$where = 'meetingid = '.$u_Appointment['id'].' and uid ='.$uid.' and status = '.$tmparrive_status;
    
        
        $tmparrive_status == 2?$data = ['status' => 3,'meettime' => time()]:$data = ['status' => 6,'deptleavetime' => time()];

        $type == 'leave'?$data = ['status' =>  6,'deptleavetime' => time()]:$data;

        $res = $this->update('arrive', $where, $data);
        if(!$res){return toJson(['message'=>'Faild','code'=>400]);}

        $u_appInfo = $this->find('view_user','id = '.$u_Appointment['app_uid']);
        $u_visterInfo =$this->find('view_user','id = '.$u_Appointment['vister_uid']);
   
        /*推送消息*/
        /*邀请人*/
        Loader::import('Wechat_OA', EXTEND_PATH);
        $wechatOA = new \Wechat_OA();

        if($tmparrive_status == 2){
            $title = '到达指定部门通知';
            $remark = "{$u_visterInfo['name']}已到达指定地点";
            $status = "到达见面地点";
        }
        if($tmparrive_status == 3){
            $title = '离开指定部门通知';
            $remark = "{$u_visterInfo['name']}已自行签退离开";
            $status = "离开见面地点";

        }

        $data = ['title'=>$type=='leave'?'离开指定部门通知':$title,
                'openid'=>$u_appInfo['openid'],
                'name'=>$u_visterInfo['name'],
                'mobile'=>$u_visterInfo['mobile'],
                'visittime'=>date('Y-m-d H:i:s',$u_Appointment['app_visittime']),
                'status'=>$type=='leave'?'离开见面地点':$status,
                'remark'=>$type=='leave'?"您已代{$u_visterInfo['name']}签离,完成见面.":$remark,
                'url'=>$url
        ];
        $result = $wechatOA->send_message($data);

        /*访客--自己*/
        /*代签提示*/
        if($tmparrive_status == 2){
            $remark = "您已到达指定地点,请耐心等待.";
            $status = "到达见面地点";
        }
        if($tmparrive_status == 3){
            $remark = "{$u_visterInfo['name']}已自行签退离开";
            $status = "您可自行离开.";

        }
        $remark_vister = '';
        if(trim($this->request->param('uid'))){$remark_vister = '受访人已代签,';}
        $wechatOA = new \Wechat_OA();
        $data = ['title'=>$title,
                'openid'=>$u_visterInfo['openid'],
                'name'=>$u_visterInfo['name'],
                'mobile'=>$u_visterInfo['mobile'],
                'visittime'=>date('Y-m-d H:i:s',$u_Appointment['app_visittime']),
                'status'=>$type=='leave'?'代签离见面地点':$status,
                'remark'=>$type=='leave'?"邀请人已代您签离,请安全离开":$remark_vister.$remark,
                'url'=>$url
        ];
        $result = $wechatOA->send_message($data);

        /*保安---不推-*/

        return toJson(['message'=>'到达见面地点成功','code'=>'200']);
    }

    public function leave_info(){
        $companyid = trim($this->request->param('companyid'));

        if(empty($companyid)){
            return toJson(['message'=>'参数不全，请检查','code'=>400]);
        }

        $arriveData = ArriveModel::where('uid',$this->uid)->where('companyid',$companyid)->where('status',3)->select();
        if(empty($arriveData)){
            return toJson(['message'=>'信息不存在','code'=>400]);
        }

        return toJson(['message'=>'获取信息成功','code'=>200,'data'=>$arriveData]);
    }

    /**
     * @Author      GNLEON
     * @HttpRequest                            |post
     * @Param                   -
     *             uid ----保安uid
     * @DateTime    2020-07-26
     * @LastTime    2020年10月12日
     * @copyright   [copyright]
     * @license     [license]
     * @return      [type]      [description]
     * @remark      确认离开  同时改变总开关app-status
     * 多人邀请对应app 需求对meet表 或 arr表 做出修改 暂时一对一邀请
     */
    public function leave(){
        $uid= trim($this->request->param('uid'))?trim($this->request->param('uid')):$this->uid;
        $meetingid = trim($this->request->param('meetingid'));
        $type = trim($this->request->param('type'))?:'';

        if(empty($uid)){
            return toJson(['message'=>'参数错误','code'=>400]);
        }

        $checkrole = $this->find('view_user','id = '.$uid);
        if(empty($checkrole)){return toJson(['message'=>'用户不存在','code'=>400]);}
        //if($checkrole['roleid'] != 6){return toJson(['message'=>'没有此权限','code'=>400]);}

        if(!empty($meetingid)){
            $data = $this->find($this->table_arrived,'meetingid = '.$meetingid);
            if(empty($data)){
                return toJson(['message'=>'信息不存在','code'=>400]);
                }
        }
        $meetingData = $this->find('meeting','id = '.$meetingid);
        if(empty($meetingData)){
            return toJson(['message'=>'信息不存在','code'=>400]);
        }
        $arriveData = $this->find('arrive','meetingid = '.$meetingid);
        if(empty($arriveData)){
            return toJson(['message'=>'信息不存在','code'=>400]);
        }

        if($arriveData['status'] == 4 || $arriveData['status'] == 5){ return toJson(['message'=>'信息已确认,无需重复操作.','code'=>'400']);} 

        $where = 'id = '.$meetingid;
        $data =  [
            'security_uid' => $uid
        ];
        $updata = $this->update('meeting', $where, $data);
        if(!$updata){return toJson(['message'=>'信息不存在','code'=>400]);} 

        $where = 'meetingid = '.$meetingid;
        $data =  [
            'leavetime' => time(),
            'status' => 4
        ];
        $updata = $this->update('arrive', $where, $data);
        if(!$updata){return toJson(['message'=>'信息不存在','code'=>400]);}



        /*结束整个流程--*/
        $where = 'id = '.$meetingData['appointmentid'];
        $data = [
            'status' => 1,
            'auditing' => 1
        ];
        $updata = $this->update('appointment',$where,$data);
        if(!$updata){return toJson(['message'=>'信息不存在','code'=>400]);} 

        $u_Appointment = $this->find($this->table_meeting_view,'id = '.$meetingid);
        if(empty($u_Appointment)){return toJson(['message'=>'离开成功','code'=>200]);}
        $u_appInfo = $this->find('view_user','id = '.$u_Appointment['app_uid']);
        $u_visterInfo = $this->find('view_user','id = '.$u_Appointment['vister_uid']);
        $url ='';
        
        
        //  /*判断访客or邀请人*/
        // if($type!='list'){
        //     $where = 'companyid = '.$companyid.' and deptid = '.$deptid.' and status = 0 and uid = '.$uid.' and visittime between '.$today.' and '.$enddaytime;
        //     $u_check = $this->find('appointment', $where)!=NULL?$u_check = 'app':$u_check = 'vister';

        //     $where = 'vister_uid = '.$uid.' and companyid = '.$companyid.' and deptid = '.$deptid.' and appointment_status = 0 and arrive_status = 2 and app_visittime between '.$today.' and '.$enddaytime;
        //     $u_check_vister = $this->total($this->table_meeting_view, $where, $field = '*')==0?$u_check = $u_check:$u_check = 'vister';
        // }
        // $type == 'list'?$u_check = 'app':'';

        
        Loader::import('Wechat_OA', EXTEND_PATH);
        $wechatOA = new \Wechat_OA();
        /*推送受访人*/

        $openid = $u_appInfo['openid']; 

        $data = [
        'template_id' => '-LIJoJBts21ZGNr0rGyejjRgSzYJdMOY84ySnf-7iPI',
        'array' => [
            'first' =>'访客已正常离开公司',
            'keyword1' => $u_visterInfo['name'],
            'keyword2' => $u_visterInfo['mobile'],
            'keyword3' => date('Y-m-d H:i',time()),
            'remark'   => '访问结束！'
            ],
        ];
        $result = $wechatOA->send_WXtpl($openid,$data,$url);
    
        /*访客--自己*/
        $openid = $u_visterInfo['openid']; 

        $data = [
        'template_id' => '-LIJoJBts21ZGNr0rGyejjRgSzYJdMOY84ySnf-7iPI',
        'array' => [
            'first' =>'您已正常离开访问公司',
            'keyword1' => $u_visterInfo['name'],
            'keyword2' => $u_visterInfo['mobile'],
            'keyword3' => date('Y-m-d H:i',time()),
            'remark'   => '访问结束！'
            ],
        ];
        $result = $wechatOA->send_WXtpl($openid,$data,$url);

        //推送给保安
        $openid = $this->user->openid; 
        $url = 'http://devs.zsicp.com/h5/#/pages/securityguard/useraudit?companyid='.$u_appInfo['companyid'].'&meetingid='.$meetingid.'&door=A';
        $data = [
        'template_id' => '-LIJoJBts21ZGNr0rGyejjRgSzYJdMOY84ySnf-7iPI',
        'array' => [
            'first' =>'访客已正常离开公司',
            'keyword1' => $u_visterInfo['name'],
            'keyword2' => $u_visterInfo['mobile'],
            'keyword3' => date('Y-m-d H:i',time()),
            'remark'   => '您确认了访客的离开.'
            ],
        ];
        $result = $wechatOA->send_WXtpl($openid,$data,$url);

        return toJson(['message'=>'离开成功','code'=>200]);
    }


}
